# 文字过滤
import os
import shutil

import LConf

conf = []

# 检查是否违规
def isViolations(source, keywrods):
    for oneWrod in keywrods:
        if(oneWrod in source):
            return True
    return False
    
# 尝试打开文本文件
def fileTryOpen(fpath):
    global conf
    try:
        with open(fpath, 'r',encoding="utf-8") as fp : fileCon = fp.read()
    except :
        try :
            with open(fpath, 'r',encoding="gbk") as fp : fileCon = fp.read()
        except :
            try :
                with open(fpath, 'r',encoding="gb2312") as fp : fileCon = fp.read()
            except Exception as e :
                LConf.Wlog(conf['runlog'],repr(e),'a') 
                return False
    return fileCon

# 文件路径中查找关键词，返回文件绝对地址
def findFile(path, keywrods):
    rmList = []
    unkonws = []
    lPath = os.listdir(path)
    for one in lPath:
        onePath = path + '/' + one
        # 检查路径是否合规
        if isViolations(one, keywrods):
            # onePath = os.path.abspath(onePath)
            item = {"PATH":onePath,"DIR":one}
            rmList.append(item)
        # 检查路径下的 .txt 文件以及内容是否合规
        else:
            if not os.path.isdir(onePath):
                continue
            chilDir = os.listdir(onePath)
            for chil in chilDir:
                chilPath = onePath + '/' + chil
                h = os.path.splitext(chilPath)[1]
                if h in ['.txt', '.json']:
                    # 尝试多种编码打开文件
                    fileCon = fileTryOpen(chilPath)
                    if fileCon == False : 
                        item ={"PATH":onePath,"DIR":one}
                        unkonws.append(item)
                    elif isViolations(fileCon,keywrods) :
                        item ={"PATH":onePath,"DIR":one}
                        rmList.append(item)
    return rmList,unkonws
# 移动文件
def moveFile(recyclePath,rl):
    global conf
    if not os.path.exists(recyclePath) : 
        os.mkdir(recyclePath)
    for one in rl:
        old = one['PATH']
        new = recyclePath + one['DIR']
        shutil.move(old, new)
        outputStr = "%s ---> %s"%(old,new)
        LConf.Wlog(conf["mvlog"],outputStr,'a')
        print(outputStr)
def main():
    global conf
    # 载入关键词
    keywords = LConf.Ltxt('./keywords.txt')
    # 载入配置文件
    conf = LConf.LConf('./conf.json')
    # 筛选含有关键词的文件
    workRoot = input("输入文章缓存目录：")
    # workRoot = './test'
    if(workRoot == '') :
        workRoot = conf['fileWhere']
    else :
        workRoot = workRoot.replace('\\','/')
    rl,uk = findFile(workRoot, keywords)
    # 移动到回收站
    moveFile(conf["recPath"],rl)
    # 移动到未知目录
    moveFile(conf['unknown'],uk)
    input("按任意键退出")
if __name__ == '__main__':
    main()
